package com.andaily.web.controller.validator;

import com.andaily.domain.dto.account.AccountFormDTO;
import com.andaily.domain.dto.account.AccountTypeDTO;
import com.andaily.domain.shared.MatchUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

/**
 * @author Shengzhao Li
 */
public class AccountFormValidator implements Validator {
    @Override
    public boolean supports(Class<?> clazz) {
        return clazz.equals(AccountFormDTO.class);
    }

    @Override
    public void validate(Object target, Errors errors) {
        AccountFormDTO accountForm = (AccountFormDTO) target;

        validateType(errors, accountForm.getAccountType());
        validateDate(errors, accountForm.getAccountDate());
        validateAmount(errors, accountForm.getAmount());
    }

    private void validateAmount(Errors errors, String amount) {
        if (StringUtils.isBlank(amount) || !MatchUtils.isBigDecimal(amount)) {
            errors.rejectValue("amount", null, "金额有误");
        }
    }

    private void validateDate(Errors errors, String accountDate) {
        if (StringUtils.isBlank(accountDate)) {
            errors.rejectValue("accountDate", null, "日期为空");
        }
    }

    private void validateType(Errors errors, AccountTypeDTO accountType) {
        String guid = accountType.getGuid();
        if (StringUtils.isBlank(guid)) {
            errors.rejectValue("accountType.guid", null, "类型为空");
        }
    }
}
